package cn.com.anypay.manager.common.annotation;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Collectors;

/**
 * 服务元数据注解和处理器
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface ServiceMetadata {
    /**
     * 服务名称
     */
    String name();

    /**
     * 服务版本
     */
    String version() default "1.0.0";

    /**
     * 构建时间戳
     */
    String buildTimestamp() default "";

    /**
     * 服务元数据处理器
     */
    @Configuration
    class Processor implements BeanPostProcessor {
        private static final Logger logger = LoggerFactory.getLogger(Processor.class);
        private static final String INFO_PATH = "www/info.txt";
        private static String serviceName = "Unknown Service";

        @Override
        public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
            ServiceMetadata buildInfo = AnnotationUtils.findAnnotation(bean.getClass(), ServiceMetadata.class);

            if (buildInfo != null) {
                // 存储服务名称
                serviceName = buildInfo.name();
            }

            return bean;
        }

        // 通用的 details 方法实现
        @RestController
        @RequestMapping("/api/anon/info")
        public static class DefaultInfoController {
            private static final Logger logger = LoggerFactory.getLogger(DefaultInfoController.class);

            @GetMapping("/details")
            public ResponseEntity<String> getInfoDetails() {
                try {
                    Path infoPath = Paths.get(INFO_PATH);
                    if (Files.exists(infoPath)) {
                        // 使用UTF-8编码读取文件内容，避免乱码问题
                        String content = Files.readAllLines(infoPath, StandardCharsets.UTF_8).stream()
                                .collect(Collectors.joining("\n"));
                        return ResponseEntity.ok()
                                .contentType(new MediaType(MediaType.TEXT_PLAIN, StandardCharsets.UTF_8))
                                .body(content);
                    } else {
                        return ResponseEntity.notFound().build();
                    }
                } catch (IOException e) {
                    logger.error("Error reading info.txt", e);
                    return ResponseEntity.internalServerError().body("Error reading info file");
                }
            }

            @GetMapping("/hello")
            public ResponseEntity<String> hello() {
                return ResponseEntity.ok()
                        .contentType(MediaType.TEXT_PLAIN)
                        .body("Hello World, " + serviceName + "!");
            }
        }
    }
}